﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace ud_Links.Data
{
    public class ud_LinkDB
    {
        private int moduleId;
        public int ModuleId
        {
            get { return moduleId; }
        }
        private LinkDB db;
        /// <summary>
        /// Initializes a new instance of the ud_LinkDB class.
        /// </summary>
        public ud_LinkDB(int moduleId)
        {
            this.moduleId = moduleId;
            db = new LinkDB();
        }

        public ud_Link GetByGuid(Guid linkGuid)
        {
            ud_Link result;
            var links = from l in db.ud_Links
                        where l.Guid.Equals(linkGuid)
                        select l;
            result = links.FirstOrDefault();
            return result;
        }

        public List<ud_Link> GetAll()
        {
            List<ud_Link> result= new List<ud_Link>();
            var links = from l in db.ud_Links
                        select l;
            result = links.ToList();
            return result;
        }

        public bool Insert(string name, string link)
        {
            bool result = false;
            ud_Link l = new ud_Link();
            l.Guid = Guid.NewGuid();
            l.Name = name;
            l.Link = link;
            l.ModuleId = moduleId;
            db.ud_Links.InsertOnSubmit(l);
            try
            {
                db.SubmitChanges();
                result = true;
            }
            catch
            {
                result = false;                
            }
            return result;
        }

        public bool Detele(Guid linkGuid)
        {
            bool result = false;
            ud_Link l = GetByGuid(linkGuid);
            db.ud_Links.DeleteOnSubmit(l);
            try
            {
                db.SubmitChanges();
                result = true;
            }
            catch
            {
                result = false;                
            }
            return result;
        }

        public bool Update(Guid linkGuid, string name, string link)
        {
            bool result = false;
            ud_Link l = GetByGuid(linkGuid);
            if (!l.Name.Equals(name)||!l.Link.Equals(link)||!l.ModuleId.Equals(moduleId))
            {
                l.Name = name;
                l.Link = link;
                l.ModuleId = moduleId;
                try
                {
                    db.SubmitChanges();
                    result = true;
                }
                catch 
                {
                    result = false;
                }
            }
            return result;
        }
    }
}
